package com.google.gwt.indexeddb.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.JsArrayString;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.RootPanel;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class IndexedDBDemo implements EntryPoint {

  HTML log;
  private IDBErrorHandler idbErrorHandler = new IDBErrorHandler() {

    @Override
    public void onerror(IDBErrorEvent event) {
      p("Error code " + event.getCode() + ", message: " + event.getMessage());
    }
  };

  /**
   * this function is used for logging in both eclipse console, on webpage and on chrome's console
   * 
   * @param s a log string
   */
  public void p(String s) {
    System.out.println(s);
    log.setHTML(log.getHTML() + s + "<br/>");
    cp(s);
  }

  private final native void cp(String o)/*-{
		console.log(o);
  }-*/;

  private final void pb() {
    p("----------------------------");
  }

  IndexedDB idb;
  IDBDatabase idbDatabase;
  String version = "v0";

  public void onModuleLoad() {
    log = new HTML();
    RootPanel.get("logContainer").add(log);

    p("start loading module");
    idb = IndexedDB.create();
    // get db
    open();

    p("Done!!!");
  }

  private void open() {
    IDBRequest dbRequest = idb.open("tododb");
    dbRequest.setOnError(idbErrorHandler);
    dbRequest.setOnSuccess(new IDBSuccessHandler() {

      public void onsuccess(IDBSuccessEvent event) {
        p("DB Return successfully: " + event.getType());
        idbDatabase = (IDBDatabase) event.getResult();
        if (!version.equals(idbDatabase.getVersion())) {
          // set version
          p("Wrong version detected, set new version!");
          IDBRequest setVersionRequest = idbDatabase.setVersion("v0");
          setVersionRequest.setOnSuccess(new IDBSuccessHandler() {

            @Override
            public void onsuccess(IDBSuccessEvent event) {
              // create objectStore
              p("Set version successfully, now create objectStore");
              idbDatabase.createObjectStore("todo", "timeStamp", false);

              getall();
            }

          });
        } else {

          getall();
        }

      }
    });
  }

  private JSONObject createJson(String json) {
    return (JSONObject) JSONParser.parseStrict(json);
  }

  private final native JsArrayString createJsArraryString(String str) /*-{
		return [ str ];
  }-*/;

  private void writedata(IDBObjectStore idbObjectStore) {
    JSONObject data = createJson("{\"testKey1\":\"testValue1\",\"testKey2\":\"testValue2\"}");
    // IDBRequest writeRequest = idbObjectStore.add(data);
    IDBRequest writeRequest = idbObjectStore.add("key1", "val1");
    writeRequest.setOnSuccess(new IDBSuccessHandler() {

      @Override
      public void onsuccess(IDBSuccessEvent event) {
        p("writeSuccess!");
      }
    });
  }

  private void getall() {
    JsArrayString jsArrayString = createJsArraryString("todo");
    // add more by jsArrayString.push("new");
    IDBTransaction idbTransaction =
        idbDatabase.transaction(jsArrayString, IDBTransaction.READ_WRITE_CHROME);
    IDBObjectStore idbObjectStore = idbTransaction.objectStore("todo");
    p("ObjectStore name = " + idbObjectStore.getName());

    writedata(idbObjectStore);
    
    IDBRequest cursorReq = idbObjectStore.openCursor();
    cursorReq.setOnSuccess(new IDBSuccessHandler() {

      @Override
      public void onsuccess(IDBSuccessEvent event) {
        p("Got data: " + event.getResult().toString());
      }
    });
  }
}
